import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HeroService } from '../../services/hero.service';
import { NzMessageService, NzModalService, UploadFile, UploadFilter } from 'ng-zorro-antd';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import { options } from '../../common/areaoption';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})

export class RegisterComponent implements OnInit {

  constructor(private heroService: HeroService,
              private fb: FormBuilder,
              private router: Router,
              private message: NzMessageService,
              private modalService: NzModalService) {
    this.randomNum=Math.random();
    this.codeUrl=host+"/code?key="+this.randomNum; 
  }

  validateForm: FormGroup;
  btn_loading=false;
  public errorTips:string;
  public codeUrl:string;
  public companyUrl:string;
  public randomNum:number;
  public uploadCode:number;
  public selectArea:number;
  public checkUsername:number;
  public checkComName:number;
  public companyLogo=host+"/plupload";
  public licenseImg=host+"/plupload";
  public fileList=[];
  public nzOptions = options;
  public values: any[] = ['请选择地区'];
  public onChanges(values: any): void {
    console.log(this.values);
    if(this.values[1]){
      this.selectArea=0;
    }
    if(this.values.length==0){
      this.selectArea=-1;
    }
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }
  }

  confirmationValidator = (control: FormControl): { [ s: string ]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  };

  phoneNUmberValidator = (control: FormControl): { [ s: string ]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (!(/^1\d{10}$/.test(control.value))) {
      return { confirm: true, error: true };
    }
  };
  
  
  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required ] ],
      password: [ null, [ Validators.required ] ],
      checkPassword: [ null, [ Validators.required, this.confirmationValidator ] ],
      captcha : [ null, [ Validators.required ] ],
      phoneNumberPrefix: [ '+86' ],
      phoneNumber: [ null, [ Validators.required ] ],
      name: [ null, [ Validators.required ] ],
      remember: [ true ]
    });
  }
  
  changeCode(){
    this.randomNum=Math.random();
    this.codeUrl=host+"/code?key="+this.randomNum; 
  }

  regiter() {
    // 获取地区
    console.log(this.values);
    
    this.validateForm.value.picKey=this.randomNum; 
    console.log(this.validateForm.value);

    if(!this.values[2]){
      this.values[2]=-1;
    }
    if(this.values[0] =="请选择地区"){
      this.selectArea=-1;
    }
    if(this.uploadCode !==0 ){
      this.uploadCode=-1;
    }
    console.log(this.uploadCode,this.values);
    if(this.uploadCode !==-1 && this.selectArea !==-1 && this.checkUsername !==-1){
      this.btn_loading=true;
      let url=host+"/register";
      let model='username='+this.validateForm.value.userName+'&pwd='+this.validateForm.value.password+'&pwds='+this.validateForm.value.checkPassword
      +'&picCode='+this.validateForm.value.captcha+'&picKey='+this.randomNum+'&mobile='+this.validateForm.value.phoneNumber
      +'&name='+this.validateForm.value.name+'&provinceId='+this.values[0]+'&cityId='+this.values[1]
      +'&districtId='+this.values[2]+'&license='+this.companyUrl;
  
      this.heroService.post(url,model).then(result=>{
          this.btn_loading=false;
          if(result.code==0){
            this.modalService.success({
              nzTitle: '提示',
              nzContent: '注册成功，请等待审核通过再登录'
            });
            this.router.navigate(['/login']);
          }else if(result.code==602){
            this.errorTips=result.msg;
            this.changeCode();
            this.validateForm.get('captcha').setValue('');
          }else{
            this.errorTips=result.msg;
            this.changeCode();
          }
      })
    }
  }

  // 筛选判断上传图片格式
  filters: UploadFilter[] = [
    {
      name: 'type',
      fn  : (fileList: UploadFile[]) => {
        const filterFiles = fileList.filter(w => ~['image/png','image/gif','image/jpg','image/jpeg','image/bmp'].indexOf(w.type));
        if (filterFiles.length !== fileList.length) {
          this.message.error(`只能上传图片`);
          return filterFiles;
        }
        return fileList;
      }
    }
  ];
  // 获取上传图片返回信息
  licenseChange(info: any): void {
    if (info.type=="success") {
      this.uploadCode=0;
      info.file.url = info.file.response.url;
      this.companyUrl = info.file.url;
      this.message.success('上传成功'); 
    }
    if (info.type=="removed") {
      this.message.success('删除成功'); 
    }
    if(info.fileList.length>1){
      this.message.error('只能上传一张图片！'); 
      info.fileList.splice(1,1);
    }
  }
  // 判断账号是否可用
  checkUser(){
    if(this.validateForm.value.userName){
      //只能输入字母、数字、下划线的组合
      let regex=/^[a-zA-Z0-9][\w-_]{5,13}$/g;
      if(regex.test(this.validateForm.value.userName)){
        this.checkUsername=0;
        let url=host+"/check/acount/username?username="+this.validateForm.value.userName;
        this.heroService.get(url).then(result=>{
          this.checkUsername=result.code;
        })
      }else{
        this.checkUsername=-1;
      }
    }
  }
  // 判断公司名称是否可用
  checkName(){
    if(this.validateForm.value.name){
      let url=host+"/check/merchant/name?name="+this.validateForm.value.name;
      this.heroService.get(url).then(result=>{
        this.checkComName=result.code;
      })
    }
  }
  usernameOnFocus(){
    this.checkUsername=0;
  }
  nameOnFocus(){
    this.checkComName=0;
  }
  cancelErrorTips(){
    this.errorTips="";
  }
  checkMobile(){
    this.validateForm.get('phoneNumber')!.setValidators(this.phoneNUmberValidator);
    this.validateForm.get('phoneNumber')!.markAsDirty();
    this.validateForm.get('phoneNumber')!.updateValueAndValidity();
  }
  clearCheckMobile(){
    this.validateForm.get('phoneNumber')!.clearValidators();
    this.validateForm.get('phoneNumber')!.markAsPristine();
    this.validateForm.get('phoneNumber')!.updateValueAndValidity();
  }
}
